<template>
  <div class="container mult-files-upload-container" v-loading="uploadLoading" >
    <el-upload
      v-if="!item.readonly"
      class="upload-demo"
      :headers="headers"
      :show-file-list="false"
      :action="item.action"
      :before-upload="beforeAvatarUpload"
      :on-success="handelSuccessUpload"
      :on-error="handelErrorUpload"
      multiple
    >
      <div class="el-form-item el-form-item--feedback el-form-item--small" :title="item.label">
        <label for="concattel" class="el-form-item__label" :style="'width: '+item.labelWidth">{{ item.label }}</label>
        <div class="el-form-item__content" :style="'margin-left: '+item.labelWidth">
          <el-button size="small" type="primary">点击上传</el-button> <span class="tips"> {{ tips }} </span>
        </div>
      </div>
      <div>
      </div>
    </el-upload>
    <div class="form-border mult-el-dialog-body-div">
      <div class="form-title" v-if="item.readonly">
        附件信息
      </div>
      <viewer class="mult-look-container" :images="uploadFileUrlList" ref="uploadViewer">
        <div class="image-div" v-for="(file,index) in uploadFileList" :key="index" @mouseenter="toolbarShow = index" @mouseleave="toolbarShow = ''">
          <a v-if="file.type != 'image'" :href="file.src" class="image-viewer" :class="file.type+'-view'" title="点击图片下载" download></a>
          <img
            v-if="file.type == 'image'"
            class="image-viewer"
            :ref="'uploadViewer' + index"
            :src="file.src"
            title="点击图片预览" 
          />
          <transition v-if="toolbarShow === index && !item.readonly" name="slide-fade">
            <div class="image-toolbar">
              <div class="image-toolbar-box del">
                <i class="el-icon-delete image-toolbar-del" title="删除" @click="handleDel(index)"></i>
              </div>
            </div>
          </transition>
        </div>
      </viewer>
    </div>
  </div>
</template>

<script>
import { matchType } from "@/util/upload";

export default {
  props: {
    item: {
      type: Object,
      required: true
    },
    value: Array,
    tips: String
  },
  data() {
    return {
      toolbarShow: '',
      uploadLoading: false,
      multUploadListVisible: false,
      multUploadListTitle: "",
      uploadFileList: [],
      headers: {
        uid: this.$store.getters.userInfo.id,
        token: this.$store.getters.token
      }
    };
  },
  watch: {
    value: {
      deep: true, // 深度监听
      immediate: true,
      handler(val) {
        for (var i = 0; i < val.length; i++) {
          this.$set(val[i], 'type', matchType(val[i].key))
        }
        this.uploadFileList = val;
        console.log("multUploadListvalue", val);
      }
    }
  },
  computed: {
    imageUrl() {
      let _url = "";
      if (this.uploadFileList.length > 0) {
        _url = this.uploadFileList[0].src;
      }
      return _url;
    },
    uploadFileUrlList() {
      let _arr = [];
      this.uploadFileList.forEach(element => {
        if (element.hasOwnProperty('src') && element.src != "" && element.hasOwnProperty('type') && element.type == 'image') {
          _arr.push(this.GLOBAL.proxyUrl + element.src);
        }
      });
      console.log("uploadFileUrlList", _arr);
      return _arr;
    }
  },
  methods: {
    //上传之前操作
    beforeAvatarUpload(file) {
      console.log(file);
      this.uploadLoading = true;

      if (this.item.hasOwnProperty('tag_limits') && parseInt(this.item.tag_limits) != 0) {
        if (this.uploadFileList.length + 1 > parseInt(this.item.tag_limits)) {
          this.$message.error('最多允许上传' + this.item.tag_limits + '个文件')
          return false
        }
      }

      //判断上传文件大小
      if(this.item.size && this.item.size != '' && this.item.size != 0){
        const isLt2M = file.size / 1024 < Number(this.item.size);
        let isMinSize = true
        if (this.item.hasOwnProperty('minsize')) {
          isMinSize = file.size / 1024 > Number(this.item.minsize);
        }
        if (!isLt2M || !isMinSize) {
          let numStr = this.item.size + 'KB'
          if(Number(this.item.size) / 1024  > 0){
            numStr = Math.round((Number(this.item.size) / 1024) * 100) / 100 + 'MB'
          }
          if (this.item.hasOwnProperty('sizeError')) {
            this.$message.error(this.item.sizeError);
          } else if(this.item.hasOwnProperty('minsize')) {
            let minnumStr = this.item.minsize + 'KB'
            if(Number(this.item.minsize) / 1024  > 0){
              minnumStr = Math.round((Number(this.item.minsize) / 1024) * 100) / 100 + 'MB'
            }
            this.$message.error('上传文件大小不能小于 '+ minnumStr +',不能超过 ' + numStr + '!');
          } else {
            this.$message.error('上传文件大小不能超过 ' + numStr + '!');
          }
          this.uploadLoading = false
          return false
        }
      }
      //判断上传文件类型
      if (this.item.hasOwnProperty('fileType') && this.item.fileType.length > 0) {
        let matchFileType = matchType(file.name);
        const isFileType =
          matchFileType.indexOf(this.item.fileType.join(",")) != -1;
        if (!isFileType) {
          this.$message.error("上传文件格式不正确!");
          this.uploadLoading = false;
          return isFileType;
        }
      }

      if (this.item.hasOwnProperty('fileTypeSuffix') && this.item.fileTypeSuffix.length > 0) {
        let suffix = ''
        try {
          var flieArr = file.name.split('.');
          suffix = flieArr[flieArr.length - 1];
        } catch (err) {
          suffix = '';
        }
        const isFileTypeSuffix = suffix.indexOf(this.item.fileTypeSuffix.join(',')) != -1
        if (!isFileTypeSuffix) {
          this.$message.error('上传文件格式不正确,为 '+this.item.fileTypeSuffix.join(',')+' 格式!');
          this.uploadLoading = false
          return isFileTypeSuffix
        }
      }

      return true;
    },
    // 删除文件
    handleDel(index) {
      this.uploadFileList.splice(index, 1);
      this.$emit('uploadChange', { fileList: this.uploadFileList})
    },
    // 文件上传成功
    handelSuccessUpload(response) {
      console.log(this.value);
      console.log(response);
      this.uploadLoading = false;
      if (response.code === 10000) {
        this.$set(response.data, 'type', matchType(response.data.key))
        this.uploadFileList.push(response.data);
        this.$emit('uploadChange', { fileList: this.uploadFileList})
      } else {
        this.$message.error(response.message);
      }
    },
    // 上传失败
    handelErrorUpload(err) {
      console.log(err);
      this.uploadLoading = false
      this.$message.error(err);
    }
  }
};
</script>

<style scoped="scoped" lang="scss">
.tips {
  color: red;
  margin-left: 10px;
}
.columnImg {
  max-width: 100px;
  max-height: 30px;
}
.mult-files-upload-container {
  text-align: left;
  .mult-el-dialog-body-div {
    min-height: 240px;
    .mult-look-container {
      padding: 12px;
      display: inline-block;
      .image-div {
        position: relative;
        display: inline-block;
        margin: 0 10px
      }
      .image-viewer {
        width: 240px;
        height: 160px;
        cursor: pointer;
        display: inline-block;
      }
    }
  }
  .image-toolbar {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 3;
    width: 100%;
    height: 40px;
    line-height: 40px;
    // background: rgba(255, 255, 255, .2);
    .image-toolbar-box {
      float: right;
      margin: 4px 8px 0 0;
      width: 32px;
      height: 32px;
      line-height: 32px;
      text-align: center;
      border-radius:2px;
      font-size: 16px;
      cursor: pointer;
    }
    .image-toolbar-box.del {
      background: #4285F4;
      color: #fff;
    }
    .image-toolbar-box.update {
      background: #fff;
      color: #333;
    }
  }
  .slide-fade-enter-active {
    transition: all 0.3s ease;
  }
  .slide-fade-leave-active {
    transition: all 0.8s cubic-bezier(1, 0.5, 0.8, 1);
  }
  .slide-fade-enter, .slide-fade-leave-to
    /* .slide-fade-leave-active for below version 2.1.8 */ {
    transform: translateY(-40px);
    opacity: 0;
  }
}
</style>
